package logic

import (
	"github.com/gin-gonic/gin"
	"iot-base/auth/svc"
	"sort"
)

type HisLogic struct {
}

func NewHisLogic() *HisLogic {
	return &HisLogic{}
}

func (l *HisLogic) QueryHis(stationId string, page, size int, classType, startTime, endTime string) ([]map[string]interface{}, error) {
	result, err := svc.Dao.THisData.QueryHisByTime(stationId, page, size, classType, startTime, endTime)
	if err != nil {
		return nil, err
	}
	if result == nil {
		return []map[string]interface{}{}, nil
	}
	temp := map[int64]map[string]interface{}{}
	for index := range result {
		dateTime := result[index].PickTime.Format("2006-01-02 15:04:05")
		key := result[index].PickTime.Unix()
		if _, ok := temp[key]; !ok {
			temp[key] = make(map[string]interface{})
			temp[key]["datetime"] = dateTime
			temp[key]["dateunix"] = result[index].PickTime.Unix()
		}
		//value, _ := decimal.NewFromFloat(result[index].Value).Round(2).Float64()
		temp[key][result[index].ModelID+"#"+result[index].Field] = gin.H{
			"value":  result[index].Value,
			"status": result[index].Status,
		}
	}
	resp := make([]map[string]interface{}, 0, len(temp))
	for _, v := range temp {
		resp = append(resp, v)
	}
	// map 是无序的 需要重新排序
	sort.Slice(resp, func(i, j int) bool {
		return resp[i]["dateunix"].(int64) > resp[j]["dateunix"].(int64)
	})
	return resp, nil
}

func (l *HisLogic) QueryHisTotal(stationId string, classType, startTime, endTime string) (int64, error) {
	return svc.Dao.THisData.QueryHisByTimeCount(stationId, classType, startTime, endTime)
}
